//from表单序列化成json
$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

//日期格式转换
Date.prototype.format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
		}
	}
	return fmt;
};

//计算时间差 type[-1(默认): 计算得到毫秒;0:计算得到秒;1:计算得到分;2:计算得到时;3:计算得到天;] fixed: 四舍五入后保留小数位数
Date.prototype.difference = function(time, type, fixed) {
	if (time) {
		try {
			time = new Date(time);
			if (time) {
				var difference = time.getTime() - this.getTime(); //时间差的毫秒数
				if (difference < 0) difference *= -1;
				if (!type && type !== 0) type = -1;
				if (type > -1) difference /= 1000;
				if (type > 0) difference /= 60;
				if (type > 1) difference /= 60;
				if (type > 2) difference /= 24;
				return fixed ? difference.toFixed(fixed) : difference;
			} else {
				console.error("请输入要计算的时间");
			}
		} catch (e) {
			console.error(e)
		}
	}
	return null;
}

/**
 * @function escapeHTML 转义html脚本 < > & " '
 * @param s -
 *            字符串
 */
function escapeHTML(s) {
	s = "" + s;
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g,
		"&apos;");
}

/**
 * @function unescapeHTML 还原html脚本 < > & " '
 * @param s -
 *            字符串
 */
function unescapeHTML(s) {
	s = "" + s;
	return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(
		/&apos;/g, "'");
}

/* 可设置长度以及进制的唯一标识码 */
function get$UUID(len, radix) {
	var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	var uuid = [],
		i;
	radix = radix || chars.length;

	if (len) {
		// Compact form
		for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
	} else {
		// rfc4122, version 4 form
		var r;

		// rfc4122 requires these characters
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		// Fill in random data.  At i==19 set the high bits of clock sequence as
		// per rfc4122, sec. 4.1.5
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
	}
	return uuid.join('');
}

/**
 * 秒转成时分秒的形式
 * @param value
 * @returns {string}
 */
function formatSeconds(value) {
	var secondTime = parseInt(value); // 秒
	var minuteTime = 0; // 分
	var hourTime = 0; // 小时
	if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
		//获取分钟，除以60取整数，得到整数分钟
		minuteTime = parseInt(secondTime / 60);
		//获取秒数，秒数取佘，得到整数秒数
		secondTime = parseInt(secondTime % 60);
		//如果分钟大于60，将分钟转换成小时
		if (minuteTime > 60) {
			//获取小时，获取分钟除以60，得到整数小时
			hourTime = parseInt(minuteTime / 60);
			//获取小时后取佘的分，获取分钟除以60取佘的分
			minuteTime = parseInt(minuteTime % 60);
		}
	}
	var result = "" + parseInt(secondTime) + "秒";

	if (minuteTime > 0) {
		result = "" + parseInt(minuteTime) + "分" + result;
	}
	if (hourTime > 0) {
		result = "" + parseInt(hourTime) + "时" + result;
	}
	return result;
}

/**
 * 结束编辑状态并保存当前值
 * @param tagId 标签id
 * @returns {boolean}
 */
function endEditing(tableId, index) {
	if ($('#' + tableId).datagrid('validateRow', index)) {
		$('#' + tableId).datagrid('endEdit', index);
		$('#' + tableId).datagrid('beginEdit', index);
		return true;
	} else {
		$.messager.alert("错误", "您有信息未填写完善", "error");
		return false;
	}
}
var _$editRowMid = 1;
/**
 * 添加一列
 * @param tableId
 */
function addRow(tableId, detaultData) {
	if (!detaultData) detaultData = {};
	var data = $.extend({
		"mid": -_$editRowMid,
		"action": "editing",
	}, detaultData);
	$('#' + tableId).datagrid('appendRow', data);
	_$editRowMid++;
	var index = $('#' + tableId).datagrid('getRows').length - 1;
	$('#' + tableId).datagrid('beginEdit', index);
}

/**
 * 保存一列数据
 * @param tableId
 * @param index
 * @param url
 */
function saveRow(tableId, mid, url) {
	var index = $("#" + tableId).datagrid('getRowIndex', mid);
	if (endEditing(tableId, index)) {
		var row = $("#" + tableId).datagrid('selectRow', index).datagrid('getSelected'),
			data = {};
		$.extend(data, row);
		data.mid = data.mid < 0 ? "" : data.mid;
		var method = row.mid >= 0 ? "edit" : "add";
		App.post(url + method, data, function(result) {
			if (result && result.success) {
				if (result.obj) row.mid = result.obj.mid;
				else if (result.response) row.mid = result.response.mid;
				row.action = "";
				$("#" + tableId).datagrid('refreshRow', index);
				$.messager.alert("成功", "保存成功", "success");
			} else {
				$.messager.alert("失败", "保存失败", "error");
			}
		}, function(msg) {
			if (!msg) msg = "保存失败";
			$.messager.alert("失败", msg, "error");
		});
	}
}

/**
 * 删除选中列
 * @param tagId
 */
function deleteRow(tableId, mid, url) {
	var index = $("#" + tableId).datagrid('getRowIndex', mid);
	if (mid >= 0) {
		App.remove(mid, url, function() {
			$('#' + tableId).datagrid('deleteRow', index);
		});
	} else {
		$('#' + tableId).datagrid('deleteRow', index);
	}
}

/**
 * 编辑当前列
 * @param index
 * @param row
 * @param tagId
 */
function editRow(tableId, mid) {
	var index = $("#" + tableId).datagrid('getRowIndex', mid);
	$("#" + tableId).datagrid('selectRow', index);
	$("#" + tableId).datagrid('getSelected').action = "editing";
	$("#" + tableId).datagrid('refreshRow', index);
	$("#" + tableId).datagrid('beginEdit', index);
}

/**
 * 数据字典对象
 **/
var Dic = function() {
	return {
		/**
		 * 根据字典码获取字典描述
		 * @param dics 字典项列表
		 * @param code 字典码
		 * @returns {*}
		 */
		showName: function(dics, code) {
			for (var i = 0; i < dics.length; i++) {
				if (dics[i].code + "" == code + "") {
					return dics[i].name
				}
			}
		},
	};

}();

var localStorageManage = function() {
	return {
		/**
		 * 表格缓存
		 * @param tableId
		 * @param formId
		 */
		set: function(tableId, formId) {
			if (!formId) formId = 'searchForm';
			if (!tableId) tableId = 'table';
			if (!window.localStorage) {
				console.log("浏览器不支持localstorage");
			} else {
				var key = "table_" + tableId + formId,
					filterRules = App.filterRules[tableId] || [],
					searchData = {};
				if ($("#" + formId).length > 0) {
					key += "_form_" + formId;
					var searchForm = $('#' + formId).serializeArray();
					if (filterRules && filterRules.length > 0) {
						for (var i = 0; i < filterRules.length; i++) {
							for (var j = 0; j < searchForm.length; j++) {
								if (searchForm[j].name == filterRules[i].field) {
									if (searchForm[j].value) {
										searchData[searchForm[j].name] = searchForm[j].value;
									}
									filterRules[i].value = searchForm[j].value;
									break;
								}
							}
						}
					}
				}
				var opts = $("#" + tableId).datagrid("options");
				if ($("#" + tableId).data('treegrid')) {
					opts = $("#" + tableId).treegrid("options");
				}
				if (opts.filterRules && opts.filterRules.length > 0) {
					for (var i = 0; i < opts.filterRules.length; i++) {
						var boo = true;
						for (var j = 0; j < filterRules.length; j++) {
							if (opts.filterRules[i].field == filterRules[j].field) {
								boo = false;
								break;
							}
						}
						if (boo) {
							filterRules.push(opts.filterRules[i]);
							searchData[opts.filterRules[i].field] = opts.filterRules[i].value;
						}
					}
				}

				key += window.location.pathname;
				window.localStorage.setItem(key, JSON.stringify({
					searchData: searchData,
					queryParams: {
						page: opts.pageNumber || 1,
						rows: opts.pageSize,
						filterRules: opts.filterStringify(filterRules)
					}
				}));
			}
		},
		/**
		 * 表格缓存获取
		 * @param tableId
		 * @param formId
		 * @returns {{}|any}
		 */
		get: function(tableId, formId) {
			if (!formId) formId = 'searchForm';
			if (!tableId) tableId = 'table';
			var key = "table_" + tableId + formId;
			if ($("#" + formId).length > 0) {
				key += "_form_" + formId;
			}
			key += window.location.pathname;
			var item = window.localStorage.getItem(key);
			if (item) {
				try {
					return JSON.parse(item);
				} catch (e) {
					return item;
				}
			}
			return {
				searchData: {},
				queryParams: {}
			};
		},
		/**
		 * 数据缓存
		 * @param key
		 * @param data
		 */
		setData: function(key, data) {
			if (!window.localStorage) {
				console.log("浏览器不支持localstorage");
			} else {
				key += window.location.pathname;
				window.localStorage.setItem(key, JSON.stringify(data));
			}
		},
		/**
		 * 数据缓存获取
		 * @param key
		 * @returns {null|any}
		 */
		getData: function(key) {
			key += window.location.pathname;
			var item = window.localStorage.getItem(key);
			if (item) {
				try {
					return JSON.parse(item);
				} catch (e) {
					return item;
				}
			}
			return null
		}
	}
}();

/**
 * 计算辅助--不使用与大数据计算
 */
var MathUtil = function() {
	return {
		//加
		add: function(arg1, arg2) {
			var r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length;
				arg1 = parseInt(arg1.toString().replace('.',''));
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
				arg2 = parseInt(arg2.toString().replace('.',''));
			} catch (e) {
				r2 = 0
			}
			
			if(r1 > r2) arg2 *= Math.pow(10, r1 - r2);
			else if(r1 < r2) arg1 *= Math.pow(10, r2 - r1);
			m = Math.pow(10, Math.max(r1, r2));
			return (arg1 + arg2) / m;
		},
		//减
		reduce: function(arg1, arg2) {
			var r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length;
				arg1 = parseInt(arg1.toString().replace('.',''));
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
				arg2 = parseInt(arg2.toString().replace('.',''));
			} catch (e) {
				r2 = 0
			}
			
			if(r1 > r2) arg2 *= Math.pow(10, r1 - r2);
			else if(r1 < r2) arg1 *= Math.pow(10, r2 - r1);
			m = Math.pow(10, Math.max(r1, r2));
			return (arg1 - arg2) / m;
		},
		//乘
		ride: function(arg1, arg2) {
			var r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length;
				arg1 = parseInt(arg1.toString().replace('.',''));
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
				arg2 = parseInt(arg2.toString().replace('.',''));
			} catch (e) {
				r2 = 0
			}
			
			m = Math.pow(10, r1 + r2);
			return (arg1 * arg2) / m;
		},
		//除
		except: function(arg1, arg2) {
			var r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length;
				arg1 = parseInt(arg1.toString().replace('.',''));
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
				arg2 = parseInt(arg2.toString().replace('.',''));
			} catch (e) {
				r2 = 0
			}
			
			m = Math.pow(10, r1 - r2);
			return arg1 / arg2 / m;
		},
		/** 保留小数
		 * @param {Object} arg1 要处理的数值
		 * @param {Object} arg2 保留几位小数
		 * @param {Object} roundOff 舍入模式 默认四舍五入 0：四舍五入 -1：舍去后面小数 1:舍去后面小数并进位
		 * @param {Object} isCovering 是否补位 补位后返回的是字符串，补位返回的是数值
		 */
		toFixed: function(arg1,arg2,roundOff,isCovering){
			if(!roundOff) roundOff = 0;
			arg2 = arg2 < 0 ? 0 : arg2;
			arg1 += "";
			var pp = arg1.indexOf(".");
			if(pp > 0) {//是否有小数
				var inte = arg1.substring(0,pp);
				if(arg2){//是否保留小数
					var r1;
					try {
						r1 = arg1.split(".")[1].length;
					} catch (e) {
						r1 = 0;
					}
					if(isCovering){//补位
						if(r1 <= arg2) {
							for(var i = r1; i < arg2; i++) {
								arg1 += '0';
							}
							return arg1;
						} else {
							var d = parseInt(arg1.split(".")[1].substring(0,arg2));
							if(roundOff == 1) { //舍去后面小数 1:舍去后面小数并进位
								d++;
							} else if(roundOff == 0) { //四舍五入
								var last = parseInt(arg1.split(".")[1].substring(arg2,arg2 + 1));
								if(last >= 5) d++;
							}
							return arg1.split(".")[0] + "." + d;
						}
					} else {
						if(r1 <= arg2) {
							return Number(arg1);
						} else {
							var d = parseInt(arg1.split(".")[1].substring(0,arg2));
							if(roundOff == 1) { //舍去后面小数 1:舍去后面小数并进位
								d++;
							} else if(roundOff == 0) { //四舍五入
								var last = parseInt(arg1.split(".")[1].substring(arg2,arg2 + 1));
								if(last >= 5) d++;
							}
							return Number(arg1.split(".")[0] + "." + d);
						}
					}
				} else {
					if(roundOff == -1) { //舍去后面小数
						return Number(inte);
					} else if(roundOff == 1) { //舍去后面小数 1:舍去后面小数并进位
						return Number(inte) + 1;
					} else { //四舍五入
						var d = parseInt(arg1.split(".")[1].substring(0,1));
						return Number(inte) + (d < 5 ? 0 : 1);
					}
				}
			} else {
				return Number(arg1);
			}
		}
	};
}();